<?php
/**
 * 菜单管理
 * 2018/11/5
 * ╔═════╗                 ╔═╗ ╔═╗
 * ║ ╔═══╝                 ║ ║ ║ ║
 * ║ ╚═══╦══╦══╦═════╦═════╣ ╚═╝ ║
 * ╚═══╗ ║  ║  ║  ║  ║  ║  ╠═╗ ╔═╝
 * ╔═══╝ ║  ║  ║  ║  ║  ║  ║ ║ ║
 * ╚═════╩═════╩══╩══╩══╩══╝ ╚═╝
 */

namespace App\Http\Controllers\Admin;


use App\Exceptions\FormException;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Spatie\Permission\Models\Permission;


class MenuController extends Controller
{

    function __construct()
    {
        $this->middleware('permission');
    }

    public function index(Request $request)
    {
        return view('Admin.menu.index');
    }

    public function getMenuList($pid=0){
        $data =  Permission::select('id','parentid','name','rule','status','ismenu','icon')
            ->orderBy('id','asc')
            ->get();

        return response()->json([
            "msg"   => '',
            "code"  => 0,
            "data"  => $data,
            "count" => $data->count(),
            "is"    => false,
            "tip"   => "加载成功"
        ]);
    }

    public function ismenu(Request $request){

        \DB::beginTransaction();
        try{
            $id = $request->input('id');
            $model = \App\Models\Permission::findOrFail($id);
            $model->ismenu = $model->ismenu == \App\Models\Permission::isMenuTrue ? \App\Models\Permission::isMenuFalse : \App\Models\Permission::isMenuTrue;
            $model->save();
        }catch (\Exception $exception){
            \DB::rollBack();
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '设置失败' );
        }
        \DB::commit();
        return $this->getResponseSuccess('设置成功');
    }

    public function status(Request $request){

        \DB::beginTransaction();
        try{
            $id = $request->input('id');
            $model = \App\Models\Permission::findOrFail($id);
            $model->status = $model->status == \App\Models\Permission::statusTrue ? \App\Models\Permission::statusFalse : \App\Models\Permission::statusTrue;
            $model->save();
        }catch (\Exception $exception){
            \DB::rollBack();
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '设置失败' );
        }
        \DB::commit();
        return $this->getResponseSuccess('设置成功');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $parentid = request()->input('parentid',0);
        return view('Admin.menu.edit',['parentid' => $parentid]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $payload  = $request->only(['parentid','name','rule','weight','icon']);

        Validator::make($payload, [
            'parentid'      => 'required',
            'name' => [
                'required',
                Rule::unique('permissions')->where('ismenu',\App\Models\Permission::isMenuTrue),
            ],
            'weight'        => 'required',
        ],[
            'parentid.required'          => '请选择上级菜单',
            'name.required'              => '请输入菜单名称',
            'name.unique'                => '菜单名称已存在',
            'weight.required'            => '请输入权重',
        ])->validate();

        \DB::beginTransaction();

        try{
            $parentInfo = \App\Models\Permission::find($payload['parentid']);
            $parentstr = '0,';
            if($parentInfo){
                $parentstr = (string) $parentInfo->parentstr.$parentInfo->id.',';
            }
            $model = new \App\Models\Permission();
            $model->parentid = $payload['parentid'];
            $model->parentstr = $parentstr;
            $model->name = $payload['name'];
            $model->rule = $payload['rule'];
            $model->weight = $payload['weight'];
            $model->icon = $payload['icon'];
            $model->ismenu = $request->input('ismenu') ?: \App\Models\Permission::isMenuFalse;
            $model->status = $request->input('status') ?: \App\Models\Permission::statusTrue;

            $model->save();

        }catch (\Exception $exception){
            \DB::rollBack();
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败' );
        }
        \DB::commit();
        return $this->getResponse('保存成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = \App\Models\Permission::findOrFail($id);
        return view('Admin.menu.edit',['data' => $data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $payload  = $request->only(['parentid','name','rule','weight','icon']);

        Validator::make($payload, [
            'parentid'      => 'required',
            'name' => [
                'required',
                Rule::unique('permissions')->where('ismenu',\App\Models\Permission::isMenuTrue)->ignore($id),
            ],
            'weight'        => 'required',
        ],[
            'parentid.required'          => '请选择上级菜单',
            'name.required'              => '请输入菜单名称',
            'name.unique'                => '菜单名称已存在',
            'rule.required'              => '请输入规则',
            'weight.required'            => '请输入权重',
        ])->validate();

        \DB::beginTransaction();

        try{
            $parentInfo = \App\Models\Permission::find($payload['parentid']);
            $parentstr = '0,';
            if($parentInfo){
                $parentstr = (string) $parentInfo->parentstr.$parentInfo->id.',';
            }
            $model = \App\Models\Permission::findOrFail($id);
            $model->parentid = $payload['parentid'];
            $model->parentstr = $parentstr;
            $model->name = $payload['name'];
            $model->rule = $payload['rule'];
            $model->weight = $payload['weight'];
            $model->icon = $payload['icon'];
            $model->ismenu = $request->input('ismenu') ?: \App\Models\Permission::isMenuFalse;
            $model->status = $request->input('status') ?: \App\Models\Permission::statusTrue;

            $model->save();

        }catch (\Exception $exception){
            \DB::rollBack();
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败' );
        }
        \DB::commit();
        return $this->getResponse('保存成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        \DB::beginTransaction();
        try{
            $permission_id_in = \App\Models\Permission::whereRaw("FIND_IN_SET(?,parentstr)",[$id])->orWhere('id',$id)->pluck('id');
            \App\Models\Permission::whereIn('id',$permission_id_in)->delete();
            \App\Models\RoleHasPermission::whereIn('permission_id',$permission_id_in)->delete();
        }catch (\Exception $exception){
            \DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '操作失败' );
        }
        \DB::commit();
        return $this->getResponse('操作成功');
    }
}